<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 01:21:39
 * @LastEditTime: 2023-09-19 13:36:50
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Traits;

use App\Models\FinanceVoucher;
use App\Models\Subject;
use App\Models\Trade;
use App\Repositories\FinanceVoucherRepository;


trait VoucherTrait
    {

    private $_voucherkey = 'code';
    public function VoucherTraitDeleting()
        {
        //凭证没有作废的情况下，反审核和作废没有合并，凭证反审的情况下，删除单据，删除凭证！
        $voucher = $this->voucher()->first();
        if ($voucher) {
            if ($voucher->status_id == 0) {
                $voucher->delete();
                }
            else {
                fail("意外错误！凭证{$voucher->code}已记账！删除失败");
                }
            }
        }
    public function voucher()
        {
        $key = $this->getVoucherkey();
        return $this->hasOne(FinanceVoucher::class, "source_value", $key)->where(function ($query) use ($key)
            {
            $query->where("source_key", $key)
                ->where("source_model", $this::class);
            });
        }
    public function getVoucherkey()
        {
        $key = $this->_voucherkey;
        if (property_exists(__CLASS__, "voucherkey"))
            $key = $this->voucherkey;
        return $key;
        }
    public function scopeFinance($query)
        {
        return $query->get()->filter(function ($v)
            {
            return $this->finance($v);
            });
        }
    public function finance($v = null)
        {
        fail("凭证需要函数finance没有创建！");
        }
    public function scopeNofinance($query)
        {
        return $query->get()->filter(function ($v)
            {
            return $this->nofinance($v);
            });
        }
    public function nofinance($orders = null)
        {
        $v = $orders ?? $this;
        if ($v->status_id == 1)
            return $v->voucher;
        if ($v->status_id != 2) {
            fail("非财审状态！，无法取消财审！");
            }
        if (($v->voucher?->status_id ?? 0) != 0) {
            fail("凭证【{$v->voucher->code}】已记账！ 操作失败！");
            }
        fauditSave($v, false);
        return $v;
        }
    public function trade()
        {
        return $this->belongsTo(Trade::class);
        }
    public function handletrade()
        {
        return $this->belongsTo(Trade::class);
        }

    public function account()
        {
        return $this->belongsTo(Subject::class);
        }
    public function subject()
        {
        return $this->belongsTo(Subject::class);
        }

    }